package com.superhelper.app.task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.superhelper.app.domain.Admin;
import com.superhelper.app.domain.Order;
import com.superhelper.app.mapper.AdminMapper;
import com.superhelper.app.mapper.OrderMapper;
import com.superhelper.app.service.ElemeService;
import com.superhelper.app.service.JHSmsHandler;
import com.superhelper.app.service.MtService;
import com.superhelper.common.Consts;
import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.TakeOutOrderProcess;
import com.superhelper.common.domain.TakeOutOrderStatus;
import com.superhelper.common.domain.TakeOutOrderType;
import com.superhelper.common.domain.baidu.BdPushEntity;
import com.superhelper.common.service.BaiduService;
import com.superhelper.common.service.FeiEService;
import com.superhelper.common.service.RedisService;
import com.superhelper.common.service.VmsService;
import com.superhelper.common.utils.JsonHelper;

@Component("takeOutOrderTask")
public class TakeOutOrderTask extends AbstractTask {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private MtService mtService;
    @Autowired
    private ElemeService elemeService;
    @Autowired
    private BaiduService baiduService;
    @Autowired
    private JHSmsHandler smsService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private VmsService vmsService;
    @Autowired
    private FeiEService feiEService;
    @Value("${online}")
    private boolean online;

    /**
     * 同步外卖订单最终状态
     */
    public void execute() {
        // TODO Auto-generated method stub
        // 清除已经完成打印的订单记录（前一天数据）
        orderMapper.deleteOrderProcessFinish();

        List<Order> list = orderMapper.getTakeout_orderNoFinish();
        log.info("TakeOutOrderTask:{}", JsonHelper.toJson(list));
        String status = null;
        for (Order o : list) {
            try {
                if (o.getType().equals(TakeOutOrderType.EleMe.getValue())) {
                    status = elemeService.getOrderStatus(o.getShopId(), o.getPlfOrderId());

                } else if (o.getType().equals(TakeOutOrderType.MeiTuan.getValue())) {
                    status = mtService.getOrderStatus(o.getShopId(), o.getPlfOrderId());

                } else if (o.getType().equals(TakeOutOrderType.BaiDu.getValue())) {
                    AuserShop shop = adminMapper.getAuserShopByType(o.getShopId(), AuserShop.SHOP_BAIDU);
                    String resp = baiduService.getOrder(shop.getSource(), o.getPlfOrderId());
                    if (StringUtils.isNoneBlank(resp)) {
                        BdPushEntity entity = JsonHelper.fromJson(resp, BdPushEntity.class);
                        @SuppressWarnings("unchecked")
                        Map<String, Object> dataMap = (Map<String, Object>) entity.getBody().get("data");
                        if (dataMap != null) {
                            @SuppressWarnings("unchecked")
                            Map<String, Object> orderMap = (Map<String, Object>) dataMap.get("order");
                            status = TakeOutOrderStatus.getByBdStatus(MapUtils.getInteger(orderMap, "status"))
                                    .getValue();
                        }
                    }
                }
                if (StringUtils.isNotBlank(status)) {
                    orderMapper.updateTakeOrderStatus(o.getId(), status);
                }
                // 清空数据
                String key = String.format(Consts.Redis.SUB_ORDER, o.getType(), o.getShopId());
                redisService.delKey(key);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                log.error("TakeOutOrderTask:{},{}", o.getPlfOrderId(), o);
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    /**
     * 定时查询没有接单的信息，超过3分钟进行短信、语音电话通知
     */
    public void executeNoReceiver() {
        // TODO Auto-generated method stub
        if (online) {
            List<Order> list = orderMapper.getTakeout_orderNoReceiver();
            long time = System.currentTimeMillis();
            final Map<Long, StringBuffer> map = new HashMap<Long, StringBuffer>();
            for (Order o : list) {
                if (time > o.getCreateAt().getTime() + 180 * 1000) {// 大于3分钟没接单
                    boolean flag = redisService.sIsMembers(com.superhelper.app.common.Consts.Cache.SMS_NORECEIVER_KEY,
                            String.valueOf(o.getId()));
                    if (!flag) {
                        redisService.saddSet(com.superhelper.app.common.Consts.Cache.SMS_NORECEIVER_KEY,
                                String.valueOf(o.getId()));
                        if (!map.containsKey(o.getAuserId())) {
                            StringBuffer sb = new StringBuffer();
                            map.put(o.getAuserId(), sb);
                        }
                        StringBuffer sb = map.get(o.getAuserId());
                        if (o.getType().equals(AuserShop.SHOP_BAIDU)) {
                            sb.append("、");
                            sb.append("百度外卖#" + o.getDaySn());
                        } else if (o.getType().equals(AuserShop.SHOP_ELEME)) {
                            sb.append("、");
                            sb.append("饿了么#" + o.getDaySn());
                        } else if (o.getType().equals(AuserShop.SHOP_MEITUAN)) {
                            sb.append("、");
                            sb.append("美团外卖#" + o.getDaySn());
                        }
                        map.put(o.getAuserId(), sb);
                    }
                }
            }
            List<Long> auserIds = new ArrayList<Long>();
            for (Long key : map.keySet()) {
                auserIds.add(key);
            }
            if (auserIds.size() > 0) {
                final List<Admin> users = adminMapper.getAdminByIds(StringUtils.join(auserIds, ","));
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        final String tpl_id = "32442";
                        for (final Admin a : users) {
                            long time1 = System.currentTimeMillis();
                            if (a.getExpireAt() != null && a.getExpireAt().getTime() > time1) {
                                // TODO Auto-generated method stub
                                String tpl_value = "#content#=" + map.get(a.getId());
                                // smsService.send(a.getUsername(), tpl_id, tpl_value);
                                log.info("executeNoReceiver sms:{}", JsonHelper.toJson(map));
                                // try {
                                // vmsService.singleCallByTts(a.getUsername());
                                // } catch (ClientException e) {
                                // TODO Auto-generated catch block
                                // log.error("{}", e);
                                // }
                            }
                        }
                    }
                });
            }
        }
    }

    /**
     * 定时查询wif打印结果（5秒执行一次）
     */
    public void executeWifiProcess() {
        // TODO Auto-generated method stub
        List<TakeOutOrderProcess> list = orderMapper.getWifiNoFinishList();
        log.info("executeWifiProcess start:{}", list.size());
        List<Long> shopIds = new ArrayList<Long>();
        long time = System.currentTimeMillis();
        for (TakeOutOrderProcess o : list) {
            boolean state = feiEService.queryOrderState(o.getPlfOrderId());
            if (state) {
                orderMapper.updateWifiProcess(o.getOrderId(), o.getPlfOrderId(), 2); // 打印完成
            } else {// 打印失败
                if (time > o.getPrintAt().getTime() + 120 * 1000) {// 大于2分钟，没有打印成功，通知商户
                    shopIds.add(Long.parseLong(o.getShopId()));
                }
            }
        }
        log.info("executeWifiProcess end:{}", list.size());
        // if (online) {
        // if (shopIds.size() > 0) {
        // List<Long> auserIds =
        // adminMapper.getAuserIdByShopIds(StringUtils.join(shopIds, ","));
        // if (auserIds.size() > 0) {
        // List<Admin> users =
        // adminMapper.getAdminByIds(StringUtils.join(auserIds, ","));
        // final String tpl_id = "32442";
        // for (final Admin a : users) {
        // threadPool.execute(new Runnable() {
        // @Override
        // public void run() {
        // // TODO Auto-generated method stub
        // smsService.send(a.getUsername(), tpl_id, "");
        // try {
        // vmsService.singleCallByTts(a.getUsername());
        // } catch (ClientException e) {
        // // TODO Auto-generated catch block
        // log.error("{}", e);
        // }
        // }
        // });
        //
        // }
        // }
        // }
        // }
    }
}
